<template>
  <page-container title="重置密码">
    <div class="password-reset-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="200px"
        label-position="left"
        class="password-form"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="form.oldPassword"
            type="password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            show-password
            placeholder="请输入6-20位新密码"
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="submitForm"
            :loading="isLoading"
          >
            {{ isLoading ? '提交中...' : '确认修改' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="password-tips">
        <h4>密码安全提示：</h4>
        <ul>
          <li>密码长度应在6-12个字符之间</li>
          <li>建议使用字母、数字和特殊字符的组合</li>
          <li>不要使用过于简单的密码，如"123456"或"password"</li>
          <li>定期更换密码可以提高账户安全性</li>
        </ul>
      </div>
    </div>
  </page-container>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { verifyPassword, updateUserToBackend } from '@/api/user' // 新增verifyPassword API

const formRef = ref()
const isLoading = ref(false)
const userStore = useUserStore()
 const router = useRouter()

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度需在6-12个字符之间'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    isLoading.value = true

    // 先验证旧密码
    const isPasswordValid = await verifyPassword({
      password: form.value.oldPassword
    })
    
    if (!isPasswordValid.data.data) {
      ElMessage.error('当前密码输入错误')
      return
    }

    // 验证通过后更新密码
    await updateUserToBackend({
      id: userStore.user.id,
      password: form.value.newPassword
    })

    ElMessage.success('密码修改成功, 请重新登陆！')
    formRef.value.resetFields()

    // 1.5秒后跳转到登录页面
    setTimeout(() => {
      router.push('/login')
    }, 1500)

  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('当前密码输入错误')
    } else {
      ElMessage.error(error.message || '密码修改失败')
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.password-reset-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .password-form {
    margin-bottom: 24px;

    :deep(.el-input) {
      max-width: 400px;
    }

    .form-actions {
      margin-top: 32px;

      .el-button {
        width: 150px;
      }
    }
  }

  .password-tips {
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 6px;
    color: #606266;

    h4 {
      margin-top: 0;
      margin-bottom: 12px;
      color: #303133;
    }

    ul {
      margin: 0;
      padding-left: 20px;

      li {
        margin-bottom: 8px;
        line-height: 1.5;
      }
    }
  }
}

@media (max-width: 768px) {
  .password-reset-container {
    padding: 16px;

    .password-form {
      :deep(.el-form-item__label) {
        text-align: left;
      }

      :deep(.el-input) {
        max-width: 100%;
      }
    }
  }
}
</style>
